# -* - coding: UTF-8 -* -
#import sys
#reload(sys) 
#sys.setdefaultencoding('utf8')
from driver import DurableDriver
import pymysql
import logging
import time
#队列驱动抽像类
class MysqlDurable(DurableDriver): 
	def create_connection(self):
		host_list = self.db_host.split(',')   #HA中有多个Mysql主机
		for host in host_list: #依次连接Mysql，直到连接成功
			try:
				self.connection = pymysql.connect(host=host, 
												port=self.db_port, 
												user=self.db_user, 
												passwd=self.db_pass, 
												db=self.db_name)
				break
			except Exception as e:
				#logger.error("connect mysql failed: %s" % e)
				 pass
		if self.connection:
			try:
				self.cursor = self.connection.cursor()
				return self.cursor
			except Exception as e:
				#logger.error("connect mysql failed: %s" % e)
				 pass
			return False
		else:
			return False
	def create(self):  
		self.db_host = self.config.get('db_server','host','localhost')
		self.db_port = self.config.get_int('db_server','port',3306)
		self.db_user = self.config.get('db_server','user','root')
		self.db_pass = self.config.get('db_server','pass','sun123')
		self.db_name = self.config.get('db_server','name','')
		self.table_name = self.config.get('db_server','table','queue_task')
		self.connection = None
		self.cursor = None
		self.create_connection()
	def ping(self):
		try:
			self.connection.ping(reconnect=True)
		except Exception as e:
			i=0
			while (not self.create_connection()) and (i<10):
				i=i+1
				logging.error("Mysql尝试重连接失败")
				time.sleep(1)
	
	def destory(self):
		try:
			self.cursor.close()
			self.connection.close()
		except Exception as e:
			pass

	def write(self,task):
		#logging.debug(self.table_name+'-----------------------------------')
		self.ping()
		try:
			self.cursor.executemany("insert into "+self.table_name+"(uuid,task,create_time,status)values(%s,%s,%s,%s)", [(task.uuid,task.toJson(),int(time.time()),1)])
			self.connection.commit()
		except Exception as e:
			logging.error('Execute SQL:'+"insert into "+self.table_name+"(uuid,task,create_time,status)values(%s,%s,%s,%s)"%(task.uuid,task.toJson(),int(time.time()),1))
			logging.exception(e)		

	
	def read(self,uuid):
		data=None
		self.ping()
		try:
			self.cursor.execute("select uuid,task,create_time,success_times,fail_times,status from  "+self.table_name+" where uuid=%s",(uuid))
			data = self.cursor.fetchone()

		except Exception as e:
			logging.error('Execute SQL:'+"select uuid,task,create_time,success_times,fail_times,status from  "+self.table_name+" where uuid=%s"%(uuid))
			logging.exception(e)	
		if data and len(data)>=5:
			return {'uuid':data[0],
					'task':data[1],
					'create_time':data[2],
					'success_times':data[3],
					'fail_times':data[4],
					'status':data[5],}
		else:
			return None
		
	def update(self,uuid,status):
		self.ping()	
		try:
			if status=='ok' or status=='':
				effect_row = self.cursor.execute("update "+self.table_name+" set update_time =%s,success_times=success_times+1 where uuid=%s", (int(time.time()),uuid))
			else:
				effect_row = self.cursor.execute("update "+self.table_name+" set update_time =%s,fail_times=fail_times+1 where uuid=%s", (int(time.time()),uuid))
		except Exception as e:
			logging.error('Execute SQL:'+"update "+self.table_name+" set update_time =%s,success_times=success_times+1 where uuid=%s"% (int(time.time()),uuid))
			logging.exception(e)	

		return effect_row
